package main

import (
	"context"
	"fmt"
	"os/exec"
	"time"
)

type result struct {
	output []byte
	err error
}

func main() {

	var (
		ctx context.Context           // 上下文
		cancelFunc context.CancelFunc // 取消上下文函数
		cmd *exec.Cmd
		resultChan chan *result
		res *result
	)

	resultChan = make(chan *result,1000)

	ctx,cancelFunc = context.WithCancel(context.TODO())

	go func() {
		var (
			output []byte
			err error
		)

		cmd = exec.CommandContext(ctx,"/bin/bash","-c","sleep 2;echo hello")
		output,err = cmd.CombinedOutput()

		resultChan<- &result{
			err:err,
			output:output,
		}
	}()

	time.Sleep(time.Second)


	// 取消上下文，即取消 Command任务
	cancelFunc()

	// 取出结果
	res = <- resultChan

	fmt.Println(res.err,string(res.output))
}
